package com.ksd.pug.clound.controller;

import com.ksd.pug.clound.api.UserServiceFeign;
import com.ksd.pug.clound.pojo.SysUser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/consumer")
@Slf4j
public class UserController {

    @Autowired
    private UserServiceFeign userServiceFeign;


    @GetMapping("/user/{id}")
    @HystrixCommand(
            // 兜底解决方案
            fallbackMethod = "fallback",
            commandProperties = {
                    // 一句话：5s(CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS)内连续请求20(CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD)次
                    //  如果20次中存在错误率>50%(CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE) 就会启动熔断，并且进入getFacllback(fallbackMethod)容错降级中
                    // 用来设置在滚动时间窗中，断路器熔断的最小请求数 默认值是：20个
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "5000"),
                    // 建议抽取tomcat最大连接数的10%~20%进行处理
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "5"),
                    // 默认是：50% 当请求的错误率大于50%的时候就熔断，然后for循环发起请求，当请求符合熔断条件时讲触发getFallback()
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "50"),
                    // 默认是 5秒，熔断多少秒去尝试请求
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "5000")
            }
    )
    public SysUser getUser(@PathVariable("id") Long id) {
        log.info("--------------getuser--------------");
        if (id == 1L) {
            throw new RuntimeException();
        }
        return userServiceFeign.findUsers(id);
    }

    public SysUser fallback(Long id) {
        SysUser sysUser = new SysUser();
        sysUser.setId(-1L);
        return sysUser;
    }
}
